package com.framework.common.config;

import com.framework.common.constant.ApiConstant;
import com.framework.common.exception.BusinessException;
import com.framework.common.model.CommonCompany;
import com.framework.common.model.CommonDept;
import com.framework.common.model.CommonUser;
import com.framework.common.model.UserInfo;
import com.framework.common.util.RedisUtil;
import com.framework.common.util.SpringUtils;
import com.framework.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;

public class SessionUtil {
    private static final Logger logger = LoggerFactory.getLogger(SessionUtil.class);

    public static CommonUser getUser() {
        try {
            return getUserInfo().getSysUser();
        } catch (Exception e) {
            logger.error("获取登录信息失败！");
        }
        return new CommonUser();
    }

    public static CommonCompany getCompany() {
        return StringUtils.isEmpty(getUserInfo().getSysCompany()) ? new CommonCompany() : getUserInfo().getSysCompany();
    }

    public static Boolean isAdmin() {
        return getUserInfo().validAdmin().getIsAdmin();
    }

    public static Boolean isSuperAdmin() {
        return getUserInfo().validSuperAdmin().getIsSuperAdmin();
    }


    public static void clear() {
        try {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            String token = request.getHeader(ApiConstant.SHARE_JSESSIONID);
            RedisUtil redisTemplate = getRedisTemplate();
            redisTemplate.del(token);
        } catch (Exception e) {
            logger.error("清空登录信息失败！");
        }
    }

    private static RedisUtil getRedisTemplate() {
        return SpringUtils.getBean(RedisUtil.class);
    }

    public static UserInfo getUserInfo() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String token = request.getHeader(ApiConstant.SHARE_JSESSIONID);
        token = token.substring(7);
        RedisUtil redisTemplate = getRedisTemplate();
        return redisTemplate.get(token);
    }

    public static boolean changeDept(final String deptId) {
        if (StringUtils.isBlank(deptId)) {
            throw new BusinessException("部门编号不能为空");
        }

        UserInfo userInfo = getUserInfo();
        CommonUser user = userInfo.getSysUser();
        user.setDeptId(deptId);
        return true;
    }

    /**
     * 获取用户所有的 authCode， 可作为列表查询的条件
     */
    public static List<String> listDeptCode() {
        UserInfo userInfo = getUserInfo();
        Set<CommonDept> set = userInfo.getDepts();
        List<String> codes = new ArrayList<>();
        set.forEach(o -> {
            if ( StringUtils.isNotBlank(o.getCode())) {
                codes.add(o.getCode());
            }
        });
        codes.stream().sorted();

        return codes;
    }

    /**
     * 获取用户当前部门的 authCode
     */
    public static String getDefaultDeptCode() {
        UserInfo userInfo = getUserInfo();
        CommonUser user = userInfo.getSysUser();
        String deptId = user.getId();
        Set<CommonDept> set = userInfo.getDepts();
        String code = null;
        if (StringUtils.isNotEmpty(set)) {
            Optional<CommonDept> optional = set.stream().filter(o -> o.getId().equals(deptId)).findFirst();
            if (optional.isPresent()) {
                code = optional.get().getCode();
            }
        }

        if (StringUtils.isBlank(code)) {
            throw new BusinessException("当前用户无默认部门");
        }

        return code;
    }

    /**
     * 获取用户当前部门的 id
     */
    public static String getDefaultDeptId() {
        UserInfo userInfo = getUserInfo();
        CommonUser user = userInfo.getSysUser();
        return user.getDeptId();
    }
}
